const {
    remote,
    ipcRenderer
} = require('electron')
const Store = require('electron-store')
const settingsStore = new Store({
    name: 'Settings'
})
const qiniuConfigArr = ['#accessKey', '#secretKey', '#bucketName', '#domainURL']

const $ = (selector) => {
    const result = document.querySelectorAll(selector)
    return result.length > 1 ? result : result[0]
}

document.addEventListener('DOMContentLoaded', () => {
    // 调用store中的值进行覆盖输入框中的值（选择文件位置）
    let savedLocation = settingsStore.get('savedFileLocation')
    if (savedLocation) {
        $('#savedFileLocation').value = savedLocation
    }
    qiniuConfigArr.forEach(selector => {
        const savedValue = settingsStore.get(selector.substr(1))
        if (savedValue) {
            $(selector).value = savedValue
        }
    })

    // 向主窗口发送最小化和关闭的信号
    $('#settings-minimize').addEventListener('click', () => {
        ipcRenderer.send('minimize')
    })
    $('#settings-close').addEventListener('click', () => {
        ipcRenderer.send('close')
    })

    $('#select-new-location').addEventListener('click', () => {
        remote.dialog.showOpenDialog({
            properties: ['openDirectory'],
            message: '选择文件的存储路径'
        }, (path) => {
            if (Array.isArray(path)) {
                $('#saved-file-location').value = path[0]
                savedLocation = path[0]
            }
        })
    })

    // 保存文件路径按钮触发
    $('#settings-save-file-location-btn').addEventListener('click', (e) => {
        settingsStore.set('savedFileLocation', savedLocation)
        remote.getCurrentWindow().close()
    })

    // 保存七牛配置信息
    $('#settings-save-qiniu-btn').addEventListener('click', (e) => {
        e.preventDefault()
        qiniuConfigArr.forEach(selector => {
            if ($(selector)) {
                const {id,value} = $(selector)
                settingsStore.set(id, value ? value : '')
            }
        })
        ipcRenderer.send('config-is-saved')
        remote.getCurrentWindow().close()
    })

    // 控制侧边栏的切换
    $('.settings-operation-name').forEach(item => {
        console.log(item)
        item.addEventListener('click', (e) => {
            $('.settings-operation-name').forEach(element => {
                element.classList.remove('settings-active-name')
            })
            e.target.classList.add('settings-active-name')
            $('.settings-form-group').forEach(element => {
                element.style.display = 'none'
            })
            $(e.target.dataset.tab).style.display = 'block'
        })
    })
})